package com.dong.agent.app;

import java.util.List;

import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Component;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;
import com.dong.agent.entity.ChatMessage;
import com.dong.agent.mapper.ChatMessageMapper;
import com.dong.agent.mapper.impl.DatabaseChatMemory;

/**
 * @description 法律助手
 * @author DongPing
 * @date 2025/05/05 21:08
 **/
@Slf4j
@Component
public class LawApp {
    private final ChatClient chatClient;

//    private final DatabaseChatMemory databaseChatMemory;

    private static final String SYSTEM_PROMPT = "本系统为多法域AI法律助手，严格遵循合规性、时效性原则，" +
            "提供24小时智能咨询（覆盖民商法、刑事合规等15领域）、文书生成及企业合规检测服务。" +
//            "采用区块链存证+ISO 27001认证架构，数据默认30天擦除。实行三级响应机制（AI应答/律师介入/紧急直连），交互需实名认证。" +
//            "依据《算法推荐管理规定》完成备案，输出标注法律来源并提示风险，重大事项强制建议线下咨询。" +
            "免责声明：内容不构成正式法律意见，涉密咨询自动终止。企业版支持API系统整合与定制报告";

    public LawApp(ChatModel dashscopeChatModel, ChatMessageMapper chatMessageMapper) {
        // 参数非空校验（关键修复）
        if (dashscopeChatModel == null || chatMessageMapper == null) {
            throw new IllegalArgumentException("依赖参数不可为空");
        }

        // 内存路径冗余代码清理（优化点）
        DatabaseChatMemory databaseChatMemory = new DatabaseChatMemory(chatMessageMapper);
        chatClient = ChatClient.builder(dashscopeChatModel)
                .defaultSystem(SYSTEM_PROMPT)
                // 显式类型转换保障类型安全（潜在风险修复）
                .defaultAdvisors(new MessageChatMemoryAdvisor(databaseChatMemory))
                .build();
    }

//    public LawApp(ChatModel dashscopeChatModel) {
//        // 初始化基于内存的对话记忆
//        ChatMemory chatMemory = new InMemoryChatMemory();
//        chatClient = ChatClient.builder(dashscopeChatModel)
//                .defaultSystem(SYSTEM_PROMPT)
//                .defaultAdvisors(
//                        new MessageChatMemoryAdvisor(chatMemory)
//                        //自定义拦截器
////                        new LawSimpleLoggerAdvisor()
//                )
//                .build();
//    }

    public String doChat(String message, String chatId) {
        ChatResponse response = chatClient
                .prompt()
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .chatResponse();
        String content = response.getResult().getOutput().getText();
        log.info("content: {}", content);
        return content;
    }

    record LawAppReport(String title, List<String> suggestions) {
    }


    public ChatMessage doChatWithReport(String message, String chatId) {
        ChatMessage chatMessage = chatClient
                .prompt()
                .system(SYSTEM_PROMPT + "每次对话后都要生成法律结果，标题为{用户名}的法律报告，内容为建议列表")
                .user(message)
                .advisors(spec -> spec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId)
                        .param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 10))
                .call()
                .entity(ChatMessage.class);
        log.info("LawAppReport: {}", chatMessage);
        return chatMessage;
    }




}

